<?php
declare(strict_types=1);
namespace cms\exam\admin\api_controller;

use cms\exam\request\AppFormRequest;
use cms\exam\request\TopicGroupFormRequest;
use cms\exam\service\AppService;
use cms\exam\service\TopicGroupService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Psr\Http\Message\ResponseInterface;

/**
 * Class AppController
 * @package cms\exam\admin\api_controller
 * @Controller(prefix="api/exam/admin_topic_group")
 */
class TopicGroupController extends CommonController
{
    /**
     * @Inject()
     * @var TopicGroupService
     */
    protected TopicGroupService $topicGroupService;

    /**
     * @param TopicGroupFormRequest $request
     * @return ResponseInterface
     * @PostMapping(path="create")
     */
    public function create(TopicGroupFormRequest $request): ResponseInterface
    {
        $form_data = $request->validated();
        $result = $this->topicGroupService->model->create($form_data);
        return $this->success('请求成功', $result);
    }

    /**
     * @param TopicGroupFormRequest $request
     * @return ResponseInterface
     * @PostMapping(path="update")
     */
    public function update(TopicGroupFormRequest $request): ResponseInterface
    {
        $form_data = $request->validated();
        $id = (int) $this->request->input('id', 0);
        $data = $this->topicGroupService->getDataById($id, true);
        $result = $this->topicGroupService->model->where('id', $data->id)->update($form_data);
        return $this->success('请求成功', $result);
    }

    /**
     * @return ResponseInterface
     * @RequestMapping(path="retrieve")
     */
    public function retrieve(): ResponseInterface
    {
        $app = $this->_getApp(true);
        $where = [
            ['app_id', '=', $app->id]
        ];
        $query = $this->topicGroupService->model->where($where);
        //region ID筛选 +++++
        $id_list = $this->request->input('id_list', '');
        if ($id_list) {
            if (strpos($id_list, ',') !== false) {
                $id_list = explode(',', $id_list);
            } else {
                $id_list = [intval($id_list)];
            }
            $query->whereIn('id', $id_list);
        }
        // endregion
        $result = $query->paginate(10);
        return $this->success('请求成功', [
            'total' => $result->total(),
            'items' => $result->items()
        ]);
    }
}